package com.jane.fragment.homepagefragment;


import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jane.adapter.homepageadapter.LiveDataAdapter;
import com.jane.bean.HomePageGridViewBean;
import com.jane.bean.JsonData;
import com.jane.config.NetConfig;
import com.jane.gzzb.R;
import com.jane.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static android.R.attr.data;
import static android.R.attr.lines;
import static android.R.attr.theme;

/**
 * A simple {@link Fragment} subclass.
 */
public class SeprinityTabLayoutFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    //申明
    private static final String TAG = SeprinityTabLayoutFragment.class.getSimpleName();
    private View mView;
    private View mHeaderView;
    private String name;
    private SwipeRefreshLayout mRefresh;
    private ListView mListView;
    private String path;
    private List<HomePageGridViewBean> mData;
    private List<HomePageGridViewBean> list;
    private LiveDataAdapter mAdapter;
    private ImageView rawcommentatorimage1, rawcommentatorimage2, rawcommentatorimage3;
    private TextView commentator1, commentator2, commentator3;
    private TextView renqi1, renqi2, renqi3;
    private TextView guanzhu1, guanzhu2, guanzhu3;

    public SeprinityTabLayoutFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_seprinity_tab_layout, null);
        mHeaderView = inflater.inflate(R.layout.header_tablayout, null);
        Bundle arguments = getArguments();
        name = arguments.getString("name", "");
        initView();
        initData();
        initListener();
        return mView;
    }

    private void initView() {
        mRefresh = (SwipeRefreshLayout) mView.findViewById(R.id.seorinity_tablayout_refresh);
        mRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.YELLOW, Color.GREEN);//样式颜色
        mListView = (ListView) mView.findViewById(R.id.seorinity_tablayout_listview);
        rawcommentatorimage1 = (ImageView) mHeaderView.findViewById(R.id.header_tablayout_rawcommentatorimage1);
        rawcommentatorimage2 = (ImageView) mHeaderView.findViewById(R.id.header_tablayout_rawcommentatorimage2);
        rawcommentatorimage3 = (ImageView) mHeaderView.findViewById(R.id.header_tablayout_rawcommentatorimage3);
        commentator1 = (TextView) mHeaderView.findViewById(R.id.header_tablayout_commentator1);
        commentator2 = (TextView) mHeaderView.findViewById(R.id.header_tablayout_commentator2);
        commentator3 = (TextView) mHeaderView.findViewById(R.id.header_tablayout_commentator3);
        renqi1 = (TextView) mHeaderView.findViewById(R.id.header_tablayout_renqi1);
        renqi2 = (TextView) mHeaderView.findViewById(R.id.header_tablayout_renqi2);
        renqi3 = (TextView) mHeaderView.findViewById(R.id.header_tablayout_renqi3);
        guanzhu1 = (TextView) mHeaderView.findViewById(R.id.item_list_tablayout_guanzhu1);
        guanzhu2 = (TextView) mHeaderView.findViewById(R.id.item_list_tablayout_guanzhu2);
        guanzhu3 = (TextView) mHeaderView.findViewById(R.id.item_list_tablayout_guanzhu3);
        //添加头布局
        mListView.addHeaderView(mHeaderView);
    }

    private void setData() {
        Utils.loadCircleImage(rawcommentatorimage1, list.get(0).getRawcommentatorimage());
        Utils.loadCircleImage(rawcommentatorimage2, list.get(1).getRawcommentatorimage());
        Utils.loadCircleImage(rawcommentatorimage3, list.get(2).getRawcommentatorimage());
        commentator1.setText(list.get(0).getCommentator());
        commentator2.setText(list.get(1).getCommentator());
        commentator3.setText(list.get(2).getCommentator());
        renqi1.setText("人气" + list.get(0).getRenqi());
        renqi2.setText("人气" + list.get(1).getRenqi());
        renqi3.setText("人气" + list.get(2).getRenqi());
    }


    //懒加载
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }


    private void initData() {
        list = new ArrayList<>();
        mData = new ArrayList<>();
        mAdapter = new LiveDataAdapter(getActivity(), mData);
        mListView.setAdapter(mAdapter);
        //地址
        String encode = null;
        try {
            encode = URLEncoder.encode(name, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        path = NetConfig.TABLAYOUTDATA_URL1 + encode + NetConfig.TABLAYOUTDATA_URL2;
        String jsonString = Utils.getJsonString(path);
        if (!TextUtils.isEmpty(jsonString)) {
            parseData(jsonString);
            ;//解析数据
        } else {
            //判断是否有网
            if (!Utils.isNetwork(getActivity())) {
                return;
            }
            //网络加载数据
            netLoadData();
        }
    }

    private void netLoadData() {
//        Log.e(TAG, "netLoadData: " + path);
        x.http().get(new RequestParams(path), new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                //保存一份
                JsonData jsonData = new JsonData();
                jsonData.setPath(path);
                jsonData.setJsonString(result);
                Utils.saveJsonString(jsonData);
//                Log.e(TAG, "onSuccess: " + result);
                mRefresh.setRefreshing(false);
                if (!TextUtils.isEmpty(result)) {
                    parseData(result);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mRefresh.setRefreshing(false);
                Log.e(TAG, "onError: ---------------");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void parseData(String result) {
        try {
            JSONObject obj0 = new JSONObject(result);
            JSONObject obj1 = obj0.getJSONObject("commentators");
            JSONArray array0 = obj1.getJSONArray("gameinfo");
            for (int i = 0; i < array0.length(); i++) {
                JSONObject obj2 = array0.getJSONObject(i);
                HomePageGridViewBean bean = new HomePageGridViewBean();
                bean.setRawcommentatorimage(obj2.optString("rawcommentatorimage"));
                bean.setCommentator(obj2.optString("commentator"));
                bean.setName(obj2.optString("name"));
                bean.setRenqi(obj2.optInt("renqi"));
                list.add(bean);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < list.size() - 3; i++) {
            mData.add(list.get(i + 3));
        }
        setData();
//        Log.e(TAG, "parseData: " + list.size());
        mAdapter.notifyDataSetChanged();
    }


    private void initListener() {
        mRefresh.setOnRefreshListener(this);
        guanzhu1.setOnClickListener(this);
        guanzhu2.setOnClickListener(this);
        guanzhu3.setOnClickListener(this);
    }

    @Override
    public void onRefresh() {
        list.clear();
        netLoadData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_list_tablayout_guanzhu1:
                guanzhu1.setText("已关注");
                guanzhu1.setTextColor(Color.GRAY);
                break;
            case R.id.item_list_tablayout_guanzhu2:
                guanzhu2.setText("已关注");
                guanzhu2.setTextColor(Color.GRAY);
                break;
            case R.id.item_list_tablayout_guanzhu3:
                guanzhu3.setText("已关注");
                guanzhu3.setTextColor(Color.GRAY);
                break;
            default:
                break;
        }
    }
}
